package com.deyuanyun.pic.pig.controller;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.deyuanyun.pic.common.tool.JXL;
import com.deyuanyun.pic.common.util.*;
import com.deyuanyun.pic.common.util.jxl.ExcelUtils;
import com.deyuanyun.pic.common.util.poi.*;
import com.deyuanyun.pic.common.util.poi.ExcelUtil;
import com.deyuanyun.pic.common.util.web.WebUtil;
import com.deyuanyun.pic.pig.controller.vo.FromPigVO;
import com.deyuanyun.pic.pig.controller.vo.PigTaskPointVO;
import com.deyuanyun.pic.pig.controller.vo.PigTaskVO;
import com.deyuanyun.pic.pig.controller.vo.ToPigVO;
import com.deyuanyun.pic.pig.domain.*;
import com.deyuanyun.pic.pig.controller.query.QueryListVO;
import com.deyuanyun.pic.settings.domain.base.Attachment;
import com.deyuanyun.pic.settings.service.base.AttachmentService;
import com.deyuanyun.pic.settings.util.DownExcelUtil;
import jxl.read.biff.BiffException;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.tool.ExceplImportCheck;
import com.deyuanyun.pic.common.tool.StaticParam;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.common.validator.imlclass.BeanValidateUtil;
import com.deyuanyun.pic.common.validator.imlclass.VResult;
import com.deyuanyun.pic.pig.service.CleanPipeLineManagerService;
import com.deyuanyun.pic.pig.service.CleanPipeLineTrackService;
import com.deyuanyun.pic.pipe.domain.BallVo;
import com.deyuanyun.pic.pipe.domain.CenterLine;
import com.deyuanyun.pic.pipe.service.PipeCenterLineService;
import com.deyuanyun.pic.settings.service.pipe.PipeLineService;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;

@Controller
@RequestMapping("/pig/cleanPipeLineTrack")
public class CleanPipeLineTrackController extends PiggingBaseController {

    @Resource
    private CleanPipeLineTrackService cleanPipeLineTrackService;
    @Resource
    private CleanPipeLineManagerService cleanPipeLineManagerService;
    @Resource
    private PipeCenterLineService pipeCenterLineService;
    @Resource
    private AttachmentService attachmentService;


    /**
     * 跳转任务追踪主页
     *
     * @return
     */
    @RequestMapping("/getCleanPipeLineTrackIndex.html")
    public ModelAndView getCleanPipeLineTrackIndex() {

        return forword("/cleanPipe/track/trackManage");
    }

    /**
     * 加载追踪列表数据
     *
     * @param taskVo
     */
    @RequestMapping("/getPigTaskTrackList.json")
    @ResponseBody
    public void getDataList(QueryListVO taskVo) {
        PageJsonBean jsonBean = new PageJsonBean();
        List<PigTaskVO> list = cleanPipeLineTrackService.getCleanPipeLineTrackIndex(taskVo);
        jsonBean.setList(list);
        AjaxSupport.sendSuccessText("","yyyy-MM-dd", jsonBean);
    }

    /**
     * 进入任务追踪详情页
     * @param taskId
     * @return
     */
    @RequestMapping("/pigTaskTrackDetail.html")
    public ModelAndView pigTaskTrackDetail(String taskId,ModelMap model) {
        Asserts.assertTrue(!StringUtils.isEmpty(taskId), "没有获取到对应的任务数据");

        model.addAttribute("taskId",taskId);
        return forword("/cleanPipe/track/seeTrack", model);
    }

    /**
     * 任务追踪
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/pigTaskTrackDetail.json")
    @ResponseBody
    public void getPigTaskTrackDetail(String taskId) {
        Asserts.assertTrue(StringUtils.isNotNullEmpty(taskId), "获取任务数据异常，请刷新页面后重试");
        //请求得到任务详细信息以及任务的收发球信息
        Map<String,Object> map = cleanPipeLineTrackService.queryPigById(taskId);

        //得到任务的跟踪点信息
        List<PigTaskPointVO>  taskPointList= cleanPipeLineTrackService.queryTaskPoint(taskId,false);
        map.put("taskPoints",taskPointList);
        //得到通过时间不为空且绝对距离靠后的跟踪点通过记录
        List<PigTaskPointVO>  passPoint= cleanPipeLineTrackService.queryTaskPoint(taskId,true);
        PigTaskPointVO maxPoint = null;
        if(null!=passPoint && passPoint.size()>0){
            maxPoint = passPoint.get(0);
        }
        map.put("maxPoint",maxPoint);

        AjaxSupport.sendSuccessText("","yyyy-MM-dd HH:mm:ss",map);
    }

    /**
     * 点击跟踪点时  得到跟踪点详情
     * @param pointId
     */
    @RequestMapping("/getPointDetail.json")
    @ResponseBody
    public void getPointDetail(String pointId,ModelMap model) {
//        Asserts.assertTrue(StringUtils.isNotNullEmpty(pointId), "获取任务数据异常，请刷新页面后重试");
        PigTaskPointVO taskPoint = cleanPipeLineTrackService.queryTaskPointById(pointId);
        model.addAttribute("taskPoint",taskPoint);
        List<Attachment> pointImgs = null;
        if(null != taskPoint){
            pointImgs = attachmentService.queryAttachment(taskPoint.getId());
        }
        model.addAttribute("pointImgs",pointImgs);

       AjaxSupport.sendSuccessText("","yyyy-MM-dd HH:mm:ss",model);
    }

    /**
     * 导出跟踪点
     *
     * @param response
     * @param taskId
     * @return
     */
    @RequestMapping("/exportTrackPoint.json")
    @ResponseBody
    public void exportTrackPoint(HttpServletResponse response, String taskId) throws Exception {
        List<PigTaskPointVO> list = cleanPipeLineTrackService.queryTaskPoint(taskId,false);
        List<String[]> result = JXL.toListFormVO(list,"yyyy-MM-dd HH:mm:ss");
        String filePath = "/template/in/trackPoint_t.xls";
        Workbook taskPointList = ExcelUtil.initWorkbook(filePath, result, 1);
        //对应项目
        PigTaskVO task = cleanPipeLineManagerService.selectByPrimaryKey(taskId);
        String fileName =null != task ? task.getTaskName()+"跟踪点信息.xls":"跟踪点信息.xls";
        WebUtil.setDownHeader(fileName);
        DownExcelUtil.fillWorkbookHead(taskPointList);
        taskPointList.write(response.getOutputStream());
    }

    /**
     * 导入跟踪点
     *
     * @param response
     * @param taskId
     * @return
     * @throws IOException
     * @throws BiffException
     */
    @RequestMapping("/importTrackPoint.json")
    @ResponseBody
    public void importTrackPoint(@RequestParam("file") MultipartFile multipartFiles, HttpServletResponse response, String taskId) throws Exception {
        Asserts.assertTrue(!ObjectUtil.isEmptyAll(multipartFiles), "附件不能为空");
        InputStream in=multipartFiles.getInputStream();
        String result= ExcelUtils.checkHead(in,TrackPointImportVO.class);
        if(result.length() > 0)
        {
            response.setStatus(503);
            AjaxResponse.sendText(response, StaticParam.getUploadFileFailMessage(result));
            return ;
        }
        in=multipartFiles.getInputStream();

        List<TrackPointImportVO> xx = ReadExcel.readExcle(TrackPointImportVO.class, multipartFiles.getInputStream(), 3, "9");


        xx = MyCollectionUtil.removeLastEmpty(xx);
        VResult b = BeanValidateUtil.vali2(xx, 1 + "");
        if (b.isRelult()) {
            int count = 0;
            try {
                count = cleanPipeLineTrackService.importTrackPoint(xx, taskId);
            }catch (Exception e){
                e.printStackTrace();
                response.setStatus(503);
                AjaxResponse.sendText(response,StaticParam.getUploadFileFailMessage("<span style='color:#ff7575'>数据错误</span><br/>"+e.getMessage()));
                return ;
            }

            if(count > 0) {
                AjaxResponse.sendText(response, StaticParam.UPLOAD_FILE_SUCCESS);
            }


        } else {
            String[] titleArr = ReadExcel.getTitle(multipartFiles, "in/trackPoint_t.xls");
            String m = b.getAllString(titleArr);
            response.setStatus(503);
            AjaxResponse.sendText(response,StaticParam.getUploadFileFailMessage(m));
        }

    }


    /**
     * 保存已完成的任务跟踪信息
     *
     * @param taskId
     * @return
     */
    @RequestMapping("/saveTaskTrack.json")
    @ResponseBody
    public void saveTaskTrack(String taskId) {
        Asserts.assertTrue(!StringUtils.isEmpty(taskId), "获取任务数据异常，请刷新页面后重试");

        int a = cleanPipeLineTrackService.saveTaskTrack(taskId);
        if (a > 0) {
            AjaxSupport.sendSuccessText("","");
        }else{
            AjaxSupport.sendFailText("","");
        }

    }

    /**
     * 得到跟踪点通过记录的图片
     */
    @RequestMapping("/getTaskPointImgs.json")
    @ResponseBody
    public void getTaskPointImgs(String businessId){
        List<Attachment> imgs = attachmentService.queryAttachment(businessId);
        AjaxSupport.sendSuccessText("",imgs);
    }

    /**
     * 加载地图显示信息
     *
     * @param taskId
     */
    @RequestMapping("/initMapData.json")
    @ResponseBody
    public void initMapData(String taskId) throws Exception {
        Asserts.assertTrue(!StringUtils.isEmpty(taskId), "数据异常，请刷新页面后重试");
        //得到任务信息
        PigTaskVO task = cleanPipeLineManagerService.getTask(taskId);
        JSONArray gisArray = new JSONArray();
        //管道gisId
        CenterLine centerLine = pipeCenterLineService.queryLineGisIdByTaskId(taskId);
        JSONObject lineGis = new JSONObject();
        lineGis.put("typeName", "pipeLine");
        if (centerLine != null) {
            lineGis.put("gisId", centerLine.getGisId());
        } else {
            lineGis.put("gisId", null);
        }
        //收发球是否易位

        lineGis.put("direction", task.getIsAdverseCurrent());

        gisArray.add(lineGis);

        //请求得到任务详细信息以及让任务的收发球信息
        Map<String,Object> ballGis = cleanPipeLineTrackService.queryPigById(taskId);

        //发球点
        FromPigVO fromPig = (FromPigVO) ballGis.get("fromPig");
        JSONObject fromPigGis = new JSONObject();
        fromPigGis.put("typeName", "fromPig");
        fromPigGis.put("gisId", fromPig.getGisId());
        fromPigGis.put("state", fromPig.getState());
        fromPigGis.put("cleanRecorder", fromPig.getRecrder());
        fromPigGis.put("cleanRecorderTime", fromPig.getSendBallsTime());
        fromPigGis.put("cleanRemark", fromPig.getRemark());

        //收球点
        ToPigVO toPig = (ToPigVO) ballGis.get("toPig");
        JSONObject toPigGis = new JSONObject();
        toPigGis.put("typeName", "toPig");
        toPigGis.put("gisId", toPig.getGisId());
        toPigGis.put("state", toPig.getState());
        toPigGis.put("cleanRecorder", toPig.getRecrder());
        toPigGis.put("cleanRecorderTime", toPig.getBackBallsTime());
        toPigGis.put("cleanRemark", toPig.getRemark());


        gisArray.add(fromPigGis);
        gisArray.add(toPigGis);
        //mark点
        List<PigTaskPointVO> MarkList = cleanPipeLineTrackService.queryTaskPoint(taskId,false);
        //得到通过时间不为空且绝对距离最靠后的跟踪点通过记录
        List<PigTaskPointVO> passPoint = cleanPipeLineTrackService.queryTaskPoint(taskId,true);
        for (PigTaskPointVO mark : MarkList) {
            JSONObject markGis = new JSONObject();
            markGis.put("typeName", "mark");
            markGis.put("gisId", mark.getGisId());
            if(passPoint!= null && passPoint.size()>0){
                PigTaskPointVO maxPoint = passPoint.get(0);
                if((task.getIsAdverseCurrent().equals("0") && mark.getMileage()<=maxPoint.getMileage()) ||
                    (task.getIsAdverseCurrent().equals("1") && mark.getMileage()>= maxPoint.getMileage())){
                    markGis.put("state","Y");
                }else{
                    markGis.put("state","N");
                }
            }else{
                markGis.put("state","N");
            }

            markGis.put("cleanRecorder", mark.getRecrder());
            markGis.put("cleanRecorderTime", mark.getPassTime());
            markGis.put("cleanRemark", mark.getCreateRemark());
            gisArray.add(markGis);
        }

        AjaxSupport.sendSuccessText("", gisArray);
    }

}
